package com.mapmymotion;

//import some stuff we need to get the example code running  
//import java.util.Timer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.jwebsocket.kit.WebSocketException;
//import org.jwebsocket.kit.WebSocketException;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

//import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
//import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.ToggleButton;
//import android.widget.ProgressBar;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

// starting the class  
public class ActivityDetail extends MapActivity implements
		OnDrawerOpenListener, OnDrawerCloseListener {
	Integer aId;
	String mylocaldate;
	JSONObject json_data;
	String is_message; // message to display in the alert dialog
	String is_error; // error message to display
	int ii_dialogid; // id of the dialog box
	private ListView listView;
	Resources res;
	String splits;
	// ProgressDialog progressBar;
	private SlidingDrawer slidingDrawer;
	ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

	ImageView image;
	private Handler mHandler = new Handler();

	private MapController mapController;
	private MapView mapView;
	List<GeoPoint> path = new ArrayList<GeoPoint>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getIntent().getExtras();
		aId = bundle.getInt("activitysummaryid");
		mylocaldate = bundle.getString("localdte");
		res = getResources();
		
		 /* progressBar = ProgressDialog.show(ActivityDetail.this,
		 * "Activity Summary", "Loading..Activity of " + mylocaldate +
		 * " Please Wait"); progressBar.show();
		 */
		
		  try {
			JWC.getIntervals(aId);
		} catch (WebSocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		  try {
			JWC.getPoints(aId);
		} catch (WebSocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		 

		setContentView(R.layout.list);

		// Get reference to SlidingDrawer
		slidingDrawer = (SlidingDrawer) this.findViewById(R.id.slidingDrawer);
		slidingDrawer.setOnDrawerOpenListener(this);
		slidingDrawer.setOnDrawerCloseListener(this);
		image = (ImageView) findViewById(R.id.drawerHandle);

	}

	@Override
	public void onResume() {
		super.onResume();
		new Thread(new Runnable() {
			public void run() {
				// ---Update the progress bar---
				mHandler.post(new Runnable() {
					public void run() {
						getActivity();
						// progressBar.hide();
					}
				});

			}

		}).start();
		// progressBar.hide();
		 
		 
/*		is_message = "Loading Interval Data";
		showDialog(Constants.MESSAGE);
		new getIntervalsThread(is_message);
		dismissDialog(ii_dialogid);
		is_message = "Loading Geo Points Data";
		new getPointsThread(is_message);
*/
	}

	public void getActivity() {

		for (int i = 0; i < 30; i++) {
			try {
				// if (JWC.jArrayIntervals != null) {
				if (JWC.getIntervals() != null) {
					;
					// json_data = JWC.jArrayIntervals.getJSONObject(0);
					json_data = JWC.getIntervals().getJSONObject(0);
					if (json_data.getInt("activitysummaryid") == aId) {
						break;
					}
				}
				Thread.sleep(1000);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		listView = (ListView) findViewById(R.id.list);
		listView.setEmptyView((TextView) findViewById(R.id.empty));
		LayoutInflater inflater = getLayoutInflater();
		View header = inflater.inflate(R.layout.rowlayoutinterval,
				(ViewGroup) findViewById(R.id.header_layout_root));
		header.setBackgroundDrawable(res
				.getDrawable(R.drawable.squarebox_input));
		listView.addHeaderView(header, null, false);

		mapView = (MapView) findViewById(R.id.mapview);
		populateList();
		SimpleAdapter intervalpoints = new SimpleAdapter(this, jsonlist,
				R.layout.rowlayoutinterval,
				new String[] { "intervalno", "pace" }, new int[] {
						R.id.intervalno, R.id.intervalpace });
		listView.setAdapter(intervalpoints);

	}

	public void onDrawerClosed() {
		// TODO Auto-generated method stub
		listView.setVisibility(ListView.VISIBLE);
		mapView.setVisibility(MapView.GONE);
		image.setImageResource(R.drawable.closearrow);
		mapView.invalidate();
	}

	public void onDrawerOpened() {
		// progressBar = ProgressDialog.show(ActivityDetail.this,
		// "Activity Map",
		// "Retrieving Map for Activity ID: " + aId + " Please Wait");
		listView.setVisibility(ListView.GONE);

		image.setImageResource(R.drawable.openarrow);
		mapView.setVisibility(MapView.VISIBLE);

		// ---do some work in background thread---
		new Thread(new Runnable() {
			public void run() {
				// ---Update the progress bar---
				mHandler.post(new Runnable() {
					public void run() {
						getPoints();
						// progressBar.dismiss();
					}
				});

			}

		}).start();

	}

	private void getPoints() {
		int iarraylength;
		mapController = mapView.getController();
		mapController.setZoom(14); // Zoon 1 is world view
		showDialog(Constants.MESSAGE);
		for (int i = 0; i < 30; i++) {
			try {
				// if (JWC.jArrayPoints != null) {
				if (JWC.getPoints() != null) {

					// json_data = JWC.jArrayPoints.getJSONObject(0);
					json_data = JWC.getPoints().getJSONObject(0);
					if (json_data.getInt("activitysummaryid") == aId) {
						break;
					}
				}
				Thread.sleep(1000);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		/*
		 * for (int i = 0; i < 60; i++) { try { Thread.sleep(1000); } catch
		 * (InterruptedException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); }
		 */
		// if (JWC.jArrayPoints != null) {
		if (JWC.getPoints() != null) {
			// iarraylength = JWC.jArrayPoints.length();
			iarraylength = JWC.getPoints().length();

			for (int icount = 0; icount < iarraylength; icount++) {
				JSONObject json_data;
				try {
					// json_data = JWC.jArrayPoints.getJSONObject(icount);
					json_data = JWC.getPoints().getJSONObject(icount);
					GeoPoint point = new GeoPoint(json_data.getInt("lat"),
							json_data.getInt("lon"));
					path.add(point);

					if (icount == 0) {
						mapController.animateTo(point);
					}

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// break;
			// }
		}
		mapView.getOverlays().clear();
		mapView.getOverlays().add(new RoutePathOverlay(path));
		dismissDialog(ii_dialogid);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private void populateList() {

		int iarraylength;
		jsonlist.clear();

		// if (JWC.jArrayIntervals != null) {
		if (JWC.getIntervals() != null) {
			// iarraylength = JWC.jArrayIntervals.length();
			iarraylength = JWC.getIntervals().length();

			for (int icount = 0; icount < iarraylength; icount++) {
				JSONObject json_data;
				HashMap<String, String> temp = new HashMap<String, String>();
				try {
					// json_data = JWC.jArrayIntervals.getJSONObject(icount);
					json_data = JWC.getIntervals().getJSONObject(icount);
					temp.put("intervalno", json_data.getString("intervalno"));
					temp.put("pace",
							json_data.getString("pace").replace('|', ':'));
					jsonlist.add(temp);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}

	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		ii_dialogid = id;
		final View layout;
		// AlertDialog alert;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		Context mContext = getApplicationContext();
		LayoutInflater inflater = (LayoutInflater) mContext
				.getSystemService(LAYOUT_INFLATER_SERVICE);

		switch (id) {
		case Constants.MESSAGE:
			builder.setTitle("Message");
			builder.setMessage("Please Wait..." + is_message);
			break;

		case Constants.MAPID:
			builder.setTitle("Activity Map");
			builder.setMessage("Retrieving Map for Activity ID...Please Wait");
			break;
		case Constants.ERROR:
			builder.setTitle("Message");
			builder.setMessage("Error: " + is_error)
					.setPositiveButton("Continue",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.dismiss();
									// mainActivity.this.finish();
								}
							})
					.setNegativeButton("Close",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.dismiss();
									ActivityDetail.this.finish();
								}
							});
			;

			break;
		}

		dialog = builder.create();
		dialog.show();
		return dialog;
	}

	class getIntervalsThread implements Runnable {
		private String ls_Message = "";

		getIntervalsThread(String s_Message) {
			if (s_Message == null) {
				throw new NullPointerException("s_message");
			}

			ls_Message = s_Message;
			Thread t = new Thread(this);
			t.start();
		}

		public void run() {
			is_message = "Loading Interval Info";
			//showDialog(Constants.MESSAGE);
			SQLList.getData(Constants.INTERVALINFO, aId.toString());
			// dismissDialog(ii_dialogid);
		}
	}

	class getPointsThread implements Runnable {
		private String ls_Message = "";

		getPointsThread(String s_Message) {
			if (s_Message == null) {
				throw new NullPointerException("s_message");
			}

			ls_Message = s_Message;
			Thread t = new Thread(this);
			t.start();
		}

		public void run() {

			SQLList.getData(Constants.POINTS, aId.toString());
			 //dismissDialog(ii_dialogid);
		}
	}

	public void ClickHandler(View v) {

		switch (v.getId()) {

		case R.id.refreshlist: // Refresh List
			ToggleButton tg_refreshlist = (ToggleButton) v;
			if (tg_refreshlist.isChecked()) {
				Toast.makeText(this, "Refresh List ", Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(this, "Please Wait...", Toast.LENGTH_LONG)
						.show();
			}
			break;

/*		case R.id.listandmap: // Refresh List
			ImageButton img_listandmap = (ImageButton) v;
			if (img_listandmap.isPressed()) {
				listView.setVisibility(ListView.GONE);

				img_listandmap.setImageResource(R.drawable.openarrow);
				mapView.setVisibility(MapView.VISIBLE);

				// ---do some work in background thread---
				new Thread(new Runnable() {
					public void run() {
						// ---Update the progress bar---
						mHandler.post(new Runnable() {
							public void run() {
								getPoints();
								// progressBar.dismiss();
							}
						});

					}

				}).start();

				
			} else {
				listView.setVisibility(ListView.VISIBLE);
				mapView.setVisibility(MapView.GONE);
				img_listandmap.setImageResource(R.drawable.mapon);
				mapView.invalidate();
			}
			break;
*/			
			
		case R.id.backbutton:
			finish();
			break;
		}

	}
}